--
-- Author: shineflag
-- Date: 2016-09-21 15:41:21
--


local skynet = require "skynet"
local proxy = require "socket_proxy"
local log = require "log"

local TAG = "CLIENT"

local function send_pkg(fd,pkg)
	local package = string.pack(">s2",pkg)
	proxy.write(fd,package)
end
local function dispatch( cli )
	local fd = cli.fd 
	proxy.subscribe(fd)

	function onproc( msg )
		-- skynet.fork( function ()
			local pkg = cli.ondata(cli,msg)
			if pkg then
				send_pkg(fd,pkg)
			else
				log.e("raise error")
			end

		-- end)
	end

	while true do
		local buf, sz = proxy.read(fd)
		local msg = skynet.tostring(buf,sz) 
		log.d(TAG,"fd[%d] read sz[%d] msg[%s]",fd,sz,msg)

		onproc(msg)
		--登录验证完
		if cli.exit then
			log.e(TAG,"cli[%s] fd[%d] exit",cli.name, cli.fd)
			return cli
		end


	end

end


local client = {}
client.send_pkg = send_pkg
client.dispatch = dispatch
client.close = proxy.close

return client
